﻿using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Test;
using IdentityServer4.Validation;
using Microsoft.AspNetCore.Authentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Yuebon.Security.Application;
using Yuebon.Security.Models;

namespace Yuebon.IdentityServer
{
    /// <summary>
    ///  自定义 Resource owner password 验证器
    /// </summary>
    public class CustomResourceOwnerPasswordValidator: IResourceOwnerPasswordValidator
    {
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            UserApp userApp = new UserApp();
            //根据context.UserName和context.Password与数据库的数据做校验，判断是否合法
            if (userApp.ValidateCredentials(context.UserName, context.Password))
            {
                User user = new UserApp().GetByUserName(context.UserName);
                context.Result = new GrantValidationResult(
                 subject: context.UserName,
                 authenticationMethod: "custom",
                 claims: GetUserClaims(user));
            }
            else
            {
                //验证失败
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential");
            }
        }

        /// <summary>
        /// 可以根据需要设置相应的Claim
        /// </summary>
        /// <returns></returns>
        private Claim[] GetUserClaims(User user)
        {
            return new Claim[]
            {
                new Claim("UserId", user.Id),
                new Claim(JwtClaimTypes.Subject,user.Id),
                new Claim(JwtClaimTypes.Name,user.RealName),
                new Claim("Account", user.Account),
                new Claim(JwtClaimTypes.NickName, user.NickName),
                new Claim(JwtClaimTypes.Role,user.RoleId)
            };
        }
    }
}
